using System;
using System.IO;
using System.Linq;
using System.Net;

namespace Storage.Core
{
	public class StorageSettings
	{
		private StorageSettings(IPAddress address, int port)
		{
			Address = address;
			Port = port;
		}

		static StorageSettings()
		{
			sync = new object();
		}

		public static StorageSettings GetInstance()
		{
			if (instance != null)
				return instance;
			lock (sync)
			{
				if (instance != null)
					return instance;
				Initialize();
				return instance;
			}
		}

		public const string SettingsFile = "storage.settings";

		public IPEndPoint EndPoint {get {return new IPEndPoint(Address, Port);}}

		public IPAddress Address { get; private set; }

		public int Port { get; private set; }

		private static void Initialize()
		{
			if (!File.Exists(SettingsFile))
				instance = new StorageSettings(IPAddress.Loopback, 44344);
			else
			{
				var lines = File
					.ReadAllLines(SettingsFile)
					.Where(line => !String.IsNullOrEmpty(line))
					.ToList();
				var address = IPAddress.Parse(lines[0]);
				var port = Int32.Parse(lines[1]);
				instance = new StorageSettings(address, port);
			}
		}

		private static volatile StorageSettings instance;
		private static readonly object sync;
	}
}